<template>
  <el-dialog
      :title="props.type == 'add' ? '添加视频信息' : '修改视频信息'"
      v-model="state.visible"
      width="600px"
      @closed="resetForm"
  >
    <el-form
        :model="state.ruleForm"
        :rules="state.rules"
        ref="formRef"
        label-width="100px"
    >
      <!-- 视频标题 -->
      <el-form-item label="视频标题" prop="title">
        <el-input
            v-model="state.ruleForm.title"
            placeholder="请输入视频标题"
            clearable
        />
      </el-form-item>

      <!-- 视频封面 -->
      <el-form-item label="视频封面" prop="coverImage">
        <el-upload
            :action="uploadImgServer"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            accept="image/*"
        >
          <img
              v-if="state.ruleForm.coverImage"
              :src="state.ruleForm.coverImage"
              class="cover"
              alt="封面"
          />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
            <span class="upload-text">点击上传封面</span>
          </el-icon>
        </el-upload>
      </el-form-item>

      <!-- 重构后的视频上传组件 -->
      <el-form-item label="视频文件" prop="videoUrl">
        <ChunkUpload
            v-model="state.ruleForm.videoUrl"
            :is-edit-mode="props.type === 'edit'"
            file-type="video/*"
            :max-size="1024 * 1024 * 1024"
            @success="handleVideoSuccess"
            @error="handleUploadError"
        />
      </el-form-item>

      <!-- 视频描述 -->
      <el-form-item label="视频描述" prop="description">
        <el-input
            v-model="state.ruleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入视频描述（最多200字）"
            maxlength="200"
            show-word-limit
        />
      </el-form-item>

      <!-- 视频作者 -->
      <el-form-item label="视频作者" prop="authorName">
        <el-input
            v-model="state.ruleForm.authorName"
            placeholder="请输入作者名称"
            clearable
        />
      </el-form-item>
      <!-- 最小年龄 -->
      <el-form-item label="最小年龄" prop="minAge">
        <el-select
          v-model="state.ruleForm.minAge"
          clearable
          placeholder="请选择最小年龄"
          style="width: 240px"
          popper-class="age-select-dropdown"
      >
        <!-- 分组标题（对应图片中的"月"分隔） -->
        <el-option-group label="年龄分组">
          <!-- 年龄选项（45-110岁，间隔5岁） -->
          <el-option
              v-for="age in ageOptions"
              :key="age"
              :value="age"
              :label="`${age}岁`"
          />
        </el-option-group>
      </el-select>
      </el-form-item>

      <!-- 最大年龄 -->
      <el-form-item label="最大年龄" prop="maxAge">
        <el-select
            v-model="state.ruleForm.maxAge"
            clearable
            placeholder="请选择最大年龄"
            style="width: 240px"
            popper-class="age-select-dropdown"
        >
          <!-- 分组标题（对应图片中的"月"分隔） -->
          <el-option-group label="年龄分组">
            <!-- 年龄选项（45-110岁，间隔5岁） -->
            <el-option
                v-for="age in ageOptions"
                :key="age"
                :value="age"
                :label="`${age}岁`"
            />
          </el-option-group>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="state.visible = false">取 消</el-button>
      <el-button
          type="primary"
          :loading="state.uploading"
          @click="submitForm"
      >确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive, ref, nextTick } from 'vue';
import { Plus } from '@element-plus/icons-vue'
import { uploadImgServer } from "../store/index.js";
import { ElMessage } from 'element-plus';
import { queryVideo, addVideo, updateVideo } from '../service/videoApi.js'
import ChunkUpload from '../components/ChunkUpload.vue'

const formRef = ref(null);
const chunkUploadRef = ref(null);

const state = reactive({
  visible: false,
  uploading: false,
  ruleForm: {
    id: '',
    title: '',
    videoUrl: '',
    authorName: "",
    description: '',
    coverImage: '',
    minAge: '',
    maxAge: ''
  },
  rules: {
    title: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
    videoUrl: [{
      required: true,
      validator: (_, value, callback) => {
        if (!value?.trim()) callback(new Error('请上传视频文件'))
        else callback()
      },
      trigger: 'change'
    }],
    authorName: [{ required: true, message: '作者不能为空', trigger: 'blur' }],
    description: [{ required: true, message: '描述不能为空', trigger: 'blur' }],
    coverImage: [{ required: true, message: '请上传封面图片', trigger: 'change' }],
    minAge: [{ required: true, message: '最小年龄不能为空', trigger: 'blur' }],
    maxAge: [{ required: true, message: '最大年龄不能为空', trigger: 'blur' }]
  },
});

const props = defineProps({
  type: String,
  reload: Function
});

// 获取详情（优化数据同步逻辑）
const getDetail = async (id) => {
  try {
    const result = await queryVideo(id);
    state.ruleForm = {
      ...result.data,
      videoUrl: result.data.videoUrl || '',
      coverImage: result.data.coverImage || ''
    };
  } catch (error) {
    ElMessage.error('获取详情失败');
  }
};

// 封面上传成功处理
const handleCoverSuccess = (res) => {
  if (res.code === 200) {
    state.ruleForm.coverImage = res.data;
    formRef.value.validateField('coverImage');
  } else {
    ElMessage.error(res.msg || '封面上传失败');
  }
};

// 视频上传回调
const handleVideoSuccess = (url) => {
  state.uploading = false;
  ElMessage.success('视频上传成功');
  formRef.value.validateField('videoUrl');
}

const handleUploadError = (err) => {
  state.uploading = false;
  ElMessage.error(`上传失败：${err.message}`);
  state.ruleForm.videoUrl = '';
};

// 表单控制逻辑
const resetForm = () => {
  chunkUploadRef.value?.reset();
  formRef.value?.resetFields();
  state.ruleForm = {
    id: '',
    title: '',
    videoUrl: '',
    authorName: "",
    description: '',
    coverImage: '',
  }
}

const open = (id) => {
  state.visible = true;
  if (id) getDetail(id);
  else resetForm();
};

// 提交表单（优化错误处理）
const submitForm = async () => {
  try {
    await formRef.value.validate();
    state.uploading = true;

    const payload = { ...state.ruleForm };
    const api = props.type === 'add' ? addVideo : updateVideo;

    await api(payload);
    ElMessage.success(`${props.type === 'add' ? '添加' : '修改'}成功`);
    state.visible = false;
    props.reload?.();
  } catch (error) {
    if (error?.errors) return; // 忽略验证错误
    ElMessage.error(error.response?.data?.message || '操作失败');
  } finally {
    state.uploading = false;
  }
};

defineExpose({ open });

const selectedAge = ref('')
const ageOptions = Array.from({ length: 14 }, (_, i) => 45 + i * 5)

</script>

<style scoped>
/* 封面样式 */
.cover {
  width: 120px;
  height: 100px;
  border-radius: 6px;
  object-fit: cover;
  border: 1px dashed var(--el-border-color);
}

.avatar-uploader-icon {
  width: 120px;
  height: 80px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--el-text-color-secondary);
  background: var(--el-fill-color-light);
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;

.upload-text {
  margin-top: 8px;
  font-size: 12px;
}
}

/* 响应式布局优化 */
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 90% !important;
  }

  :deep(.el-form-item__label) {
    width: 80px !important;
  }
}
</style>
